<template>
  <el-dialog
    v-model="visible"
    title="店铺详情"
    width="1200px"
    :before-close="handleClose"
    class="shop-detail-dialog"
  >
    <div v-loading="loading" class="shop-detail-container">
      <!-- 店铺基本信息卡片 -->
      <el-card class="shop-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">基本信息</span>
            <el-tag 
              v-if="shopInfo?.status !== undefined" 
              :type="getStatusType(shopInfo.status)"
              size="small"
            >
              {{ shopInfo?.statusName || '未知状态' }}
            </el-tag>
          </div>
        </template>
        
        <el-descriptions :column="3" border class="shop-descriptions">
          <el-descriptions-item label="店铺名称" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.shopName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="店铺编码" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.shopCode || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="店铺类型" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.shopTypeName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="所属社区" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.communityName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="所属楼栋" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.buildingName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="所属单元" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.unitName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="房间号" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.roomNumber || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="楼层" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.floorNumber || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="面积(㎡)" label-class-name="desc-label">
            <span class="desc-value">{{ formatArea(shopInfo?.area) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="租金(元/月)" label-class-name="desc-label">
            <span class="desc-value price-value">{{ formatPrice(shopInfo?.rentPrice) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系人" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.contactPerson || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.contactPhone || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="营业执照号" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.businessLicense || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="3" label-class-name="desc-label">
            <span class="desc-value">{{ shopInfo?.remark || '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 店铺图片卡片 -->
      <el-card class="shop-images-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">店铺图片</span>
            <span v-if="shopInfo?.imageInfoList?.length" class="image-count">
              共 {{ shopInfo.imageInfoList.length }} 张图片
            </span>
          </div>
        </template>
        
        <div class="images-container">
          <WebImageDisplay
            v-if="shopInfo?.imageInfoList && shopInfo.imageInfoList.length > 0"
            :images="shopInfo.imageInfoList"
            :max-display="6"
            :show-download="true"
            :show-delete="false"
            display-mode="grid"
            :show-image-info="true"
            :show-info="true"
            class="image-display"
          />
          <el-empty v-else description="暂无图片" :image-size="60" />
        </div>
      </el-card>

      <!-- 关联业主卡片 -->
      <el-card class="shop-owners-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">关联业主</span>
            <span v-if="ownerList?.length" class="owner-count">
              共 {{ ownerList.length }} 位业主
            </span>
          </div>
        </template>
        
        <div class="owners-container">
          <el-table 
            v-if="ownerList && ownerList.length > 0"
            :data="ownerList" 
            stripe 
            size="default"
            class="owners-table"
            :header-cell-style="tableHeaderStyle"
            :cell-style="tableCellStyle"
            max-height="400"
          >
            <el-table-column prop="ownerName" label="业主姓名" width="140" show-overflow-tooltip>
              <template #default="{ row }">
                <div class="owner-name-cell">
                  <span class="owner-name">{{ row.ownerName }}</span>
                  <el-tag 
                    v-if="row.isPrimary === 1" 
                    type="success" 
                    size="small" 
                    class="primary-tag"
                  >
                    主要联系人
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="ownerPhone" label="联系电话" width="140" show-overflow-tooltip>
              <template #default="{ row }">
                <span class="phone-number">{{ row.ownerPhone }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="ownerTypeName" label="业主类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag 
                  :type="row.ownerType === 1 ? 'primary' : 'warning'" 
                  size="small"
                  effect="light"
                >
                  {{ row.ownerTypeName }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="relationTypeName" label="关系类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag 
                  :type="getRelationTypeTagType(row.relationType)" 
                  size="small"
                  effect="light"
                >
                  {{ row.relationTypeName }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="companyName" label="企业名称" min-width="160" show-overflow-tooltip>
              <template #default="{ row }">
                <span v-if="row.companyName" class="company-name">{{ row.companyName }}</span>
                <span v-else class="text-placeholder">-</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="ownershipRatio" label="所有权比例" width="120" align="center">
              <template #default="{ row }">
                <span v-if="row.ownershipRatio" class="ratio-value">{{ row.ownershipRatio }}%</span>
                <span v-else class="text-placeholder">-</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="rentPrice" label="租金" width="120" align="right">
              <template #default="{ row }">
                <span v-if="row.rentPrice" class="price-text">¥{{ formatNumber(row.rentPrice) }}</span>
                <span v-else class="text-placeholder">-</span>
              </template>
            </el-table-column>
            
            <el-table-column label="租赁期间" width="200" show-overflow-tooltip>
              <template #default="{ row }">
                <span v-if="row.leaseStartDate && row.leaseEndDate" class="date-range">
                  {{ formatDate(row.leaseStartDate) }} - {{ formatDate(row.leaseEndDate) }}
                </span>
                <span v-else class="text-placeholder">-</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="statusName" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag 
                  :type="row.status === 1 ? 'success' : 'danger'" 
                  size="small"
                  effect="light"
                >
                  {{ row.statusName }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <el-empty v-else description="暂无关联业主" :image-size="80" />
        </div>
      </el-card>

      <!-- 时间信息卡片 -->
      <el-card class="shop-time-card" shadow="never">
        <template #header>
          <span class="card-title">时间信息</span>
        </template>
        
        <el-descriptions :column="2" border class="time-descriptions">
          <el-descriptions-item label="创建时间" label-class-name="desc-label">
            <span class="desc-value">{{ formatDateTime(shopInfo?.createTime) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" label-class-name="desc-label">
            <span class="desc-value">{{ formatDateTime(shopInfo?.updateTime) }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" size="default">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { shopApi } from '@/api/shop'
import WebImageDisplay from '@/components/WebImageDisplay.vue'
import type { ShopDetail } from '@/api/shop'

interface Props {
  modelValue: boolean
  shopId?: number
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)
const shopInfo = ref<ShopDetail | null>(null)
const ownerList = ref<any[]>([])


// 定义loadShopInfo函数
const loadShopInfo = async () => {
  if (!props.shopId) {
    console.log('店铺ID为空，无法加载店铺信息')
    return
  }
  
  try {
    console.log('开始加载店铺详情，shopId:', props.shopId)
    loading.value = true
    
    // 并行加载店铺详情和业主列表
    const [shopResponse, ownerResponse] = await Promise.all([
      shopApi.getShopDetail(props.shopId),
      loadOwnerList(props.shopId)
    ])
    
    console.log('店铺详情API响应:', shopResponse)
    
    if (shopResponse && shopResponse.code === 200 && shopResponse.data) {
      shopInfo.value = shopResponse.data
      console.log('店铺详情数据加载成功:', shopInfo.value)
    } else {
      console.error('API响应错误:', shopResponse)
      ElMessage.error(shopResponse?.message || '加载店铺信息失败')
    }
    
  } catch (error: any) {
    console.error('加载店铺信息异常:', error)
    
    // 处理业务错误
    if (error && error.isBusinessError) {
      ElMessage.error(error.message || '加载店铺信息失败')
    } else {
      ElMessage.error('加载店铺信息失败')
    }
  } finally {
    loading.value = false
  }
}

// 加载业主列表
const loadOwnerList = async (shopId: number) => {
  try {
    console.log('开始加载业主列表，shopId:', shopId)
    const response = await shopApi.getShopOwners(shopId)
    console.log('业主列表API响应:', response)
    
    if (response && response.code === 200 && response.data) {
      ownerList.value = response.data
      console.log('业主列表数据加载成功:', ownerList.value)
    } else {
      console.warn('业主列表API响应错误:', response)
      ownerList.value = []
    }
  } catch (error: any) {
    console.error('加载业主列表异常:', error)
    ownerList.value = []
  }
}


// 监听店铺ID变化，加载店铺信息
watch(() => props.shopId, (newShopId) => {
  if (newShopId && visible.value) {
    loadShopInfo()
  }
}, { immediate: true })

// 监听弹窗显示状态
watch(visible, (newVisible) => {
  if (newVisible && props.shopId) {
    loadShopInfo()
  }
})

// 状态类型判断
const getStatusType = (status?: number) => {
  switch (status) {
    case 1:
      return 'success'
    case 0:
      return 'danger'
    default:
      return 'info'
  }
}

// 关系类型标签类型
const getRelationTypeTagType = (relationType?: number) => {
  switch (relationType) {
    case 1:
      return 'success' // 业主
    case 2:
      return 'warning' // 租户
    case 3:
      return 'info' // 联合业主
    default:
      return 'info'
  }
}

// 表格头部样式
const tableHeaderStyle = {
  background: '#f5f7fa',
  color: '#606266',
  fontWeight: '600',
  fontSize: '14px'
}

// 表格单元格样式
const tableCellStyle = {
  fontSize: '13px',
  padding: '8px 0'
}

// 格式化面积
const formatArea = (area?: number | string) => {
  if (!area) return '-'
  if (typeof area === 'number') {
    return area.toFixed(2)
  }
  return area.toString()
}

// 格式化价格
const formatPrice = (price?: number | string) => {
  if (!price) return '-'
  if (typeof price === 'number') {
    return '¥' + price.toFixed(2)
  }
  return '¥' + price.toString()
}

// 格式化数字
const formatNumber = (num?: number | string) => {
  if (!num) return '-'
  if (typeof num === 'number') {
    return num.toFixed(2)
  }
  return num.toString()
}

// 格式化日期时间
const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 格式化日期
const formatDate = (date?: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const handleClose = () => {
  visible.value = false
  shopInfo.value = null
}
</script>

<style scoped>
/* 对话框样式 */
.shop-detail-dialog {
  .el-dialog__body {
    padding: 0;
  }
}

/* 容器样式 */
.shop-detail-container {
  padding: 0;
  background: #f8f9fa;
  min-height: 600px;
}

/* 卡片通用样式 */
.shop-info-card,
.shop-images-card,
.shop-owners-card,
.shop-time-card {
  margin-bottom: 16px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.shop-info-card:last-child,
.shop-images-card:last-child,
.shop-owners-card:last-child,
.shop-time-card:last-child {
  margin-bottom: 0;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.image-count,
.owner-count {
  font-size: 12px;
  color: #909399;
  background: #f5f7fa;
  padding: 2px 8px;
  border-radius: 4px;
}

/* 描述列表样式 */
.shop-descriptions,
.time-descriptions {
  margin: 0;
}

:deep(.desc-label) {
  background: #fafbfc !important;
  color: #606266 !important;
  font-weight: 500 !important;
  width: 120px !important;
  text-align: right !important;
  padding-right: 16px !important;
}

.desc-value {
  color: #303133;
  font-weight: 400;
}

.price-value {
  color: #67c23a;
  font-weight: 600;
}

/* 图片容器样式 */
.images-container {
  padding: 16px 0;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-display {
  width: 100%;
}

/* 业主表格容器 */
.owners-container {
  padding: 0;
}

.owners-table {
  width: 100%;
  border-radius: 6px;
  overflow: hidden;
}

/* 业主表格单元格样式 */
.owner-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.owner-name {
  font-weight: 500;
  color: #303133;
}

.primary-tag {
  margin-left: 4px;
  font-size: 10px;
  padding: 2px 6px;
}

.phone-number {
  color: #606266;
  font-family: 'Courier New', monospace;
}

.company-name {
  color: #303133;
  font-weight: 400;
}

.ratio-value {
  color: #409eff;
  font-weight: 500;
}

.price-text {
  color: #67c23a;
  font-weight: 600;
}

.date-range {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

.text-placeholder {
  color: #c0c4cc;
  font-style: italic;
}

/* 对话框底部样式 */
.dialog-footer {
  text-align: right;
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shop-detail-container {
    padding: 8px;
  }
  
  .shop-info-card,
  .shop-images-card,
  .shop-owners-card,
  .shop-time-card {
    margin-bottom: 12px;
  }
  
  .card-title {
    font-size: 14px;
  }
  
  .owners-table {
    font-size: 12px;
  }
}

/* 表格滚动条样式 */
.owners-table :deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

.owners-table :deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.owners-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.owners-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.owners-table :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 空状态样式优化 */
:deep(.el-empty) {
  padding: 40px 0;
}

:deep(.el-empty__description) {
  color: #909399;
  font-size: 14px;
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 4px;
  font-size: 12px;
}

/* 表格行悬停效果 */
.owners-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 表格边框优化 */
.owners-table :deep(.el-table) {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.owners-table :deep(.el-table th) {
  border-bottom: 1px solid #e4e7ed;
}

.owners-table :deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
}
</style>